<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge,chrome=1">
    <meta name="referrer" content="never">
    <title>WebSocket</title>
    <link rel="stylesheet" href="../lib/layui-v2.5.7/layui/css/layui.css">
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        ul {
            list-style: none;
        }

        p {
            line-height: 30px;
        }
        p.right {
            text-align: right;
        }

        p.center {
            font-size: 13px;
            color: #999;
            text-align: center;
        }

        .layui-layer-content {
            padding: 20px;
        }

        .layui-layer-content button {
            display: block;
            margin: 0 auto;
        }
    </style>
</head>
<body>
    <div class="layui-container">
        <button class="layui-btn connect">建立连接</button>
        <button class="layui-btn close">断开连接</button>
        <button class="layui-btn clear">清空聊天记录</button>

        <div class="layui-form-item" style="margin-top: 20px;">
            
            <div class="layui-input-inline">
                <input type="text" class="layui-input ipt" placeholder="请输入内容" autocomplete="off">
            </div>
            <button class="layui-btn send">发送消息</button>
        </div>

        <div class="layui-tab layui-tab-brief">
            <ul class="layui-tab-title">
                <li class="layui-this">聊天室</li> 
                <li>个人信息</li> 
            </ul>
            <ul class="layui-tab-content">
                <li class="layui-tab-item layui-show">
                    <div class="layui-card-body room">
                        
                    </div>
                </li>
                <li class="layui-tab-item info">
                    
                </li>
            </ul>
        </div>
        <div class="layui-card">
        </div>
    </div>

    <script src="../lib/layui-v2.5.7/layui/layui.all.js"></script>
    <script type="text/javascript">
        /* 
        聊天室：
            用户登录：http://bufantec.com/api/test/user/doLogin post username/password
            建立连接：ws://bufantec.com/websocket.ws/{{userId}}
            个人信息：http://www.bufantec.com/api/test/user/detail get  id

        1. 创建实例 new WebSocket(ws://url)
        2. 监听方法  ws.onmessge(e){ e.data }  ws.onopen() 连接上的监听 ws.onclose 断开连接的监听
        3. ws.send() 可以往服务器发送信息，遵循后台规定的格式
        4. 将被动断开改为主动断开
        */

        var $ = layui.$,
            form = layui.form,
            element = layui.element,
            userId = localStorage.getItem("uid"), // 先从本地获取 "xx" null
            ws = null;

        // 本地没有用户id，登录创建
        if(!userId){

            layer.open({
                type: 1,
                content: `
                <div class="layui-form">
                    <div class="layui-form-item">
                        <label class="layui-form-label">用户名</label>
                        <div class="layui-input-block">
                            <input type="text" class="layui-input" value="zhangfei" name="username" autocomplete="off"
                                lay-verify="required" value="zhanfei">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">密码</label>
                        <div class="layui-input-block">
                            <input type="password" class="layui-input" value="123456" name="password" autocomplete="off">
                        </div>
                    </div>
                    <button class="layui-btn" lay-submit lay-filter="login">提交</button>
                </div>
                `
            })
        }

        form.on("submit(login)", function (data){
            // data.field
            $.ajax({
                url: "http://bufantec.com/api/test/user/doLogin",
                type: 'POST',
                data: data.field,
                success(res){
                    // console.log(res);
                    if(res.code == "success"){
                        layer.closeAll();
                        layer.msg("登录成功", { icon: 1, time: 1500 });
                        userId = res.userId;
                        localStorage.setItem("uid", userId);
                    }
                }
            })
        })

        // 获取个人信息
        element.on("tab", function (obj){
            if(obj.index == 1){
                getInfo();
            }        
        })

        function getInfo(){
            $.ajax({
                url: "http://www.bufantec.com/api/test/user/detail",
                data: {id: userId},
                success(res){
                    $(".info").html(`
                    <p>昵称：${res.data.name }</p>
                    <p>年龄：${res.data.age }</p>
                    <p>性别：${res.data.tel }</p>
                    <p>地址：${res.data.address }</p>
                    <p>电话：${res.data.tel }</p>
                    <p>学校：${res.data.school }</p>`);
                }
            })
        }

        $(".connect").click(function (){
            if(!userId){
                layer.msg("请先登录", { icon: 4, time: 1500 });
                return;
            }
            // ws://  wss://
            ws = new WebSocket("ws://bufantec.com/websocket.ws/" + userId);

            ws.onopen = function (){
                console.log("连接成功了");
            }

            ws.onmessage = function (e){
                // console.log("后台返回的数据：", e.data);
                var msgObj = JSON.parse(e.data);
                if(/欢迎: /.test(msgObj.msg)){
                    msgObj.from.nickname = "管理员";
                }
                $(".room").append(`<p class="left">${ msgObj.from.nickname }：${ msgObj.msg }</p>`);
            }

            ws.onclose = function (){
                console.log("断开连接了");
                $(".room").append(`<p class="center">断开连接了</p>`);
            }
        })

        $(".close").click(function (){
            // 如果ws是连接状态，我们断开
            // readyState 0 未连接   1  连接中   2 关闭中   3 已关闭或有意外
            if(ws && ws.readyState == 1){
                ws.close();
            }
        })

        $(".send").click(function (){
            // 有值校验
            if(ws && ws.readyState == 1){
                // 发送信息时，使用 JSON字符串，包含 userId/msg 两个信息
                ws.send(JSON.stringify({
                    userId,
                    msg: $(".ipt").val()
                }))
                $(".ipt").val("");
            }
        })

        $(".clear").click(function (){
            $(".room").html("");
        })

        window.onbeforeunload = function (){
            if(ws && ws.readyState == 1){
                ws.close();
            }
        }
    </script>
</body>
</html>